#include "../config.h"
#include <string.h>
#include <glib.h>
#include "gam_subscription.h"
#include "inotify-sub.h"

static gboolean   is_debug_enabled = FALSE;
#define IS_W if (is_debug_enabled) g_warning

static void ih_sub_setup( ih_sub_t *sub );

ih_sub_t * ih_sub_new( const char *pathname, gboolean is_dir, guint32 flags, void *userdata ) {
  ih_sub_t *sub = NULL;
  sub = g_new0( ih_sub_t, 1 );
  sub->usersubdata = userdata;
  sub->is_dir = is_dir;
  sub->extra_flags = flags;
  sub->pathname = g_strdup( pathname );
  IS_W( "new subscription for %s being setup\n", sub->pathname );
  ih_sub_setup( sub );
  return sub;
}

void ih_sub_free( ih_sub_t *sub ) {
  if( sub->filename ) {
    g_free( sub->filename );
  }
  if( sub->dirname ) {
    g_free( sub->dirname );
  }
  g_free( sub->pathname );
  g_free( sub );
}

static gchar *ih_sub_get_dirname( gchar *pathname ) {
  return g_path_get_dirname( pathname );
}

static gchar *ih_sub_get_filename( gchar *pathname ) {
  return g_path_get_basename( pathname );
}

static
void ih_sub_fix_dirname( ih_sub_t *sub ) {
  size_t len = 0;
  g_assert( sub->dirname );
  len = strlen( sub->dirname );
  if( sub->dirname[len] == '/' ) {
    sub->dirname[len] = '\0';
  }
}

static void ih_sub_setup( ih_sub_t *sub ) {
  if( sub->is_dir ) {
    sub->dirname = g_strdup( sub->pathname );
    sub->filename = NULL;
  } else {
    sub->dirname = ih_sub_get_dirname( sub->pathname );
    sub->filename = ih_sub_get_filename( sub->pathname );
  }
  ih_sub_fix_dirname( sub );
  IS_W( "sub->dirname = %s\n", sub->dirname );
  if( sub->filename ) {
    IS_W( "sub->filename = %s\n", sub->filename );
  }
}
